package com.wf.mock.app.utils;

import java.util.Random;

import org.apache.commons.lang3.StringUtils;

/**
 * token工具类
 * 
 * @author wangyun
 *
 */
public final class TokenUtils {


	private static final String WSM_KEY = "wafer123wafer123";

	private static final String DIVIDER = "=";

	private static final int TOKEN_LENGTH = 4;
	
	public static void main(String[] args) {
		System.out.println(parseUserId("04591DC2618274FE720126DE58337E9EC870274B754DD5759B0AB32F670B0EE9611874EBA522321810D7431841F4C0C2"));
	}


	/**
	 * 从token中获取用户ID.
	 * 
	 * @param token
	 * @return String
	 */
	public static String parseUserId(String token) {
		try {
			if (StringUtils.isNoneBlank(token) && !"null".equals(token) && !"undefined".equals(token)) {
				String tokenStr = AESUtil.decrypt(token.trim(), WSM_KEY);
				String[] str = tokenStr.split(DIVIDER);
				if (str.length == TOKEN_LENGTH) {
					return str[0];
				}
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	/**
	 * 根据用户名生成token
	 * 
	 * @param userId
	 * @return
	 */
	public static String generateToken(String userId) {
		StringBuilder tokenStr = new StringBuilder().append(userId).append(DIVIDER).append(generateRandomStr(6))
				.append(DIVIDER).append(generateRandomStr(6)).append(DIVIDER).append(generateRandomStr(6));
		try {
			return AESUtil.encrypt(tokenStr.toString(), WSM_KEY);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 生成指定长度 的随机字符串
	 * 
	 * @param length
	 * @return
	 */
	public static String generateRandomStr(int length) {
		StringBuilder sb = new StringBuilder();
		Random random = new Random();
		for (int i = 0; i < length; i++) {

			if (random.nextInt(2) % 2 == 0) // 字符串
			{
				int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
				sb.append((char) (choice + random.nextInt(26)));
			} else // 数字
			{
				sb.append(random.nextInt(10));
			}
		}

		return sb.toString();
	}

}
